package com.rongshu.sendmessage.activity;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSONObject;
import com.gyf.immersionbar.ImmersionBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.base.BaseActivity;
import com.rongshu.sendmessage.base.MyApplication;
import com.rongshu.sendmessage.bean.HuoYunBean;
import com.rongshu.sendmessage.util.ClientPublicParamUtil;
import com.rongshu.sendmessage.util.ProgressDialog;
import com.rongshu.sendmessage.util.StringUtils;
import com.rongshu.sendmessage.util.ToastUtils;
import com.rongshu.sendmessage.util.downTime.MCountDownTimer;
import com.rongshu.sendmessage.util.httpUtil.HYContent;
import com.rongshu.sendmessage.util.httpUtil.IModel;
import com.rongshu.sendmessage.view.TitileLayout;

import org.json.JSONException;

import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;

public class HYRegistActivity extends BaseActivity {
    EditText password_et;
    EditText account_et;
    EditText password_et_two;
    Button regist_btn;
    EditText code_et;
    TextView getCode_btn;
    private ProgressDialog dialog;
    private MCountDownTimer countDownTimer;
    private String source;
    private String wxJson;
    private LinearLayout ll_wx_nick;
    private TextView tv_wx_nice;
    private boolean isClick=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        ImmersionBar.with(this)
//                .statusBarColor(R.color.login_color)
//                .statusBarDarkFont(true)
//                .init();
        setContentView(R.layout.activity_hyregist);
        mContext=this;
        ButterKnife.bind(this);
        source=getIntent().getStringExtra("source");
        initView();
        countDownTimer = new MCountDownTimer();
        this.countDownTimer.setOnCountDownListener(new MCountDownTimer.OnCountDownListener() {
            @Override
            public void onStop() {
                if (getCode_btn != null) {
                    getCode_btn.setText("获取验证码");
                    isClick=true;
                }
            }

            @Override
            public void onTick(long second) {
                if (getCode_btn != null) {
                    getCode_btn.setText("获取验证码");
                    String time = "发送中(%s)";
                    time = String.format(time, second);
                    getCode_btn.setText(time);
                    isClick=false;
                }
            }
        });


    }

    private void initView() {
        ll_wx_nick=findViewById(R.id.ll_wx_nick);
        tv_wx_nice=findViewById(R.id.tv_wx_nice);

        account_et=findViewById(R.id.account_et);
        account_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s!=null&&s.toString().length()>0){
                    String teamStr=s.toString();
                    if (teamStr.length()>19){
                        account_et.setText(teamStr.substring(0,19));
                        account_et.setSelection(19);
                        ToastUtils.show(mContext,"账号长度最多19位");
                    }
                }
            }
        });
        password_et_two=findViewById(R.id.password_et_two);
        password_et_two.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s!=null&&s.toString().length()>0){
                    String teamStr=s.toString();
                    if (teamStr.length()>29){
                        password_et_two.setText(teamStr.substring(0,29));
                        password_et_two.setSelection(29);
                        ToastUtils.show(mContext,"密码长度最多29位");
                    }
                }
            }
        });
        password_et=findViewById(R.id.password_et);
        password_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s!=null&&s.toString().length()>0){
                    String teamStr=s.toString();
                    if (teamStr.length()>29){
                        password_et.setText(teamStr.substring(0,29));
                        password_et.setSelection(29);
                        ToastUtils.show(mContext,"密码长度最多29位");
                    }
                }
            }
        });
        regist_btn=findViewById(R.id.regist_btn);
        code_et=findViewById(R.id.code_et);

        getCode_btn=findViewById(R.id.getCode_btn);
        TextView title = findViewById(R.id.title);
        LinearLayout titleLayLeft = findViewById(R.id.titleLayLeft);
        title.setText("注册");
        titleLayLeft.setOnClickListener(view->{
            finish();
        });
        if ("weixinLogin".equals(source)||"dialogWeixinLogin".equals(source)){
            wxJson=getIntent().getStringExtra("wxJson");
            ll_wx_nick.setVisibility(View.VISIBLE);
            try {
                org.json.JSONObject jsonObject=new org.json.JSONObject(wxJson);
                String name=jsonObject.getString("name");
                tv_wx_nice.setText(name);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }else{
            ll_wx_nick.setVisibility(View.GONE);
        }
    }



    private Intent mIntent;
    public void onClick(View view) {
        int id = view.getId();//获取验证码
        if (id == R.id.getCode_btn) {
            if(!isClick){
                return;
            }
            String account = account_et.getText().toString();
            if (StringUtils.isEmpty(account)) {
                ToastUtils.show(mContext, "手机号码不能为空！");
                return;
            }
            getVCode(account);
            //注册
        } else if (id == R.id.regist_btn) {
            String account1 = account_et.getText().toString();
            if (StringUtils.isEmpty(account1)) {
                ToastUtils.show(mContext, "手机号码不能为空！");
                return;
            }
            String password = password_et.getText().toString();
            String password_two = password_et_two.getText().toString();
            if (StringUtils.isEmpty(password) || StringUtils.isEmpty(password_two)) {
                ToastUtils.show(mContext, "密码不能为空！");
                return;
            }
            if (!password.equals(password_two)) {
                ToastUtils.show(mContext, "两次密码不一致");
                return;
            }
            if (password.length() < 8) {
                ToastUtils.show(mContext, "密码长度不能少于8位！");
                return;
            }

            String vcode = code_et.getText().toString();
            if (StringUtils.isEmpty(vcode)) {
                ToastUtils.show(mContext, "验证码不能为空！");
                return;
            }
            showProgress();
            regist(account1, password, vcode);
        }
    }
//  去注册
    private void regist(String account, String password, String vcode) {
        Map<String, String> param = new HashMap<String, String>();
        param.put("userName",account);
        param.put("password",password);
        param.put("validateCode",vcode);
        String url;
        if ("weixinLogin".equals(source)||"dialogWeixinLogin".equals(source)){
            //微信的注册
            param.put("wxuserJson",wxJson);
            param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
            url=new HYContent().WX_RegistURL;
            OkGo.<String>post(url).params(param).execute(new StringCallback() {
                @Override
                public void onSuccess(Response<String> response) {
                    IModel.AjaxResult jr = new IModel.AjaxResult(response.body(),false);
                    final int code = jr.getCode();
                    HuoYunBean huoYunBean;
                    if(code > 0) {

                        huoYunBean = JSONObject.toJavaObject(jr.getData(), HuoYunBean.class);
                        if(huoYunBean != null){
                            huoYunBean.setLoginName(account_et.getText().toString());
                            huoYunBean.setPassword(password_et.getText().toString());
                            HYContent.saveUser(huoYunBean);
                            hideProgress();
                            setResult(1000,new Intent());
                            finish();
                        }
                    }else{
                        ToastUtils.show(mContext,jr.getMsg());
                        hideProgress();
                    }
                }
                @Override
                public void onError(Response<String> response) {
                    ToastUtils.show(mContext,"操作失败");
                    hideProgress();
                }
            });
        }else{
            url=new HYContent().RegistURL;
            param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
            OkGo.<String>post(url).params(param).execute(new StringCallback() {
                @Override
                public void onSuccess(Response<String> response) {
                    IModel.AjaxResult jr = new IModel.AjaxResult(response.body(),false);
                    final int code = jr.getCode();
                    HuoYunBean huoYunBean;
                    if(code > 0) {

                        huoYunBean = new HuoYunBean();
                        JSONObject jo=new JSONObject(jr.getData());
                        String nick = jo.getString("nick");
                        huoYunBean.setNickName(nick);
                        String id = jo.getString("id");
                        huoYunBean.setUserId(id);
                        String userName = jo.getString("userName");
                        huoYunBean.setCompanyName(userName);
                        String sex = jo.getString("sex");
                        huoYunBean.setGender(sex.equals("MAN")?"1":"0");
                        huoYunBean.setLoginName(account_et.getText().toString());
                        huoYunBean.setPassword(password_et.getText().toString());
                        HYContent.saveUser(huoYunBean);
                        hideProgress();
                        setResult(1000,new Intent());
                        finish();
                    }else{
                        ToastUtils.show(mContext,jr.getMsg());
                        hideProgress();
                    }
                }
                @Override
                public void onError(Response<String> response) {
                    ToastUtils.show(mContext,"操作失败");
                    hideProgress();
                }
            });
        }
    }
    //获取验证码
    private void getVCode(String account) {
        countDownTimer.cancel();
        countDownTimer.start();
        Map<String, String> param = new HashMap<String, String>();
        param.put("userName",account);
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        String url = new HYContent().GET_CODE_URL;

        OkGo.<String>post(url).params(param).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                IModel.AjaxResult jr = new IModel.AjaxResult(response.body());
                final int code = jr.getCode();
                if (code>0){
                    ToastUtils.show(mContext,"发送验证码成功！");
                }else{
                    ToastUtils.show(mContext,jr.getMsg());
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                ToastUtils.show(mContext,"发送验证码失败！");

            }
        });
    }

    public void showProgress() {
        dialog = ProgressDialog.createDialog(this);
        dialog.show();
    }

    public void hideProgress() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }
}
